import { isProd } from '@src/const/env';
import { baseUrlDev, baseUrlPro } from '../const';
import { MutableRefObject } from 'react';

// 请求后台获取answer
export default function getChatGptAnswer({
  data,
  abortController = {} as any,
}: {
  data: any;
  abortController?: MutableRefObject<AbortController>;
}): Promise<IAnyObject> {
  // 使用fetch请求进行流式处理
  return new Promise((resolve, reject) => {
    return fetch(`${isProd ? baseUrlPro : baseUrlDev}/chat/answer`, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        Accept: 'text/event-stream',
        'Content-Type': 'application/json',
      },
      signal: abortController.current.signal,
    })
      .then((res) => {
        if (!res.body) {
          throw new Error('No response body');
        }
        if (abortController.current?.signal.aborted) {
          res.body.cancel();
        }
        resolve(res);
      })
      .catch((err) => {
        const msg = data?.msg || {};
        reject(`请求失败: ${msg?.status}:  ${msg?.message || err}`);
      });
  });
}
